import json
import os
import shutil
import time
import platform
import torch
from utils.conf import get_gpu


# check file/dir exits, if dont then creat
def check_path(file: str, mod='d', remove_old=False):
    if mod == 'd':
        if os.path.isdir(file) and remove_old:
            shutil.rmtree(file)
        if not os.path.isdir(file):
            os.mkdir(file)
    if mod == 'f':
        if os.path.isfile(file) and remove_old:
            os.remove(file)
        if not os.path.isfile(file):
            open(file, 'w')


def write_json(path: str, obj, mod='a'):
    with open(path, mod) as f:
        json.dump(obj, f)


def read_json(path: str):
    res = None
    with open(path, 'r') as f:
        res = json.load(f)
    return res


def get_timestamp():
    return int(time.time())


# according the OS and cuda to return device name --str var
def get_device() -> str:
    sys_name = platform.system()
    # mps for mac-m1/m2 and cuda:0 for Linux/Windows
    if sys_name == 'Darwin':
        return "mps" if torch.backends.mps.is_available() else "cpu"
    elif sys_name == 'Linux' or sys_name == 'Windows':
        return f"cuda:{get_gpu()}" if torch.cuda.is_available() else "cpu"
    else:
        return "cpu"
